package com.inlycat.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author jarvan4dev@163.com
 * @since 2015年8月31日下午3:04:08
 * @category
 
 
  
 **/
public class GenerateInviteCode implements Runnable {

	private Connection connection = null;
	private PreparedStatement statement = null;

	public static void main(String[] args) throws IOException {
		Thread thread = null;
		for (int i = 0; i < 11; i++) {
			thread = new Thread(new GenerateInviteCode());
			thread.start();
		}
	}

	private static String generate() {
		return StrUtils.getFileName().substring(4).toUpperCase();
	}

	@Override
	public void run() {
		try {
			Class.forName("org.mariadb.jdbc.Driver");
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/init", "root", "123456");
			for (int i = 0; i < 1000; i++) {
				String code = generate();
				if (!exsit(code)) {
					String sql = "insert into tb_code (code) values (?)";
					statement = connection.prepareStatement(sql);
					statement.setString(1, code);
					statement.execute();
				}
			}
			connection.close();
		} catch (SQLException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public boolean exsit(String code) throws SQLException {
		String sql = "select count(*) from tb_code where code=?";
		statement = connection.prepareStatement(sql);
		statement.setString(1, code);
		ResultSet resultSet = statement.executeQuery();
		
		int result = 0;
		if(resultSet.next())
			result = resultSet.getInt(1);
		return result > 0 ? true : false;
	}

}
